import subprocess
import numpy as np
import matplotlib.pyplot as plt
import os

# Shell 脚本路径
# script_path = 'run_case.sh'
script_path = os.path.abspath('run_case.sh')

# 运行 Shell 脚本
# 如果要运行算例，这里打开；如果已经运行算例，这里关闭
# 1. 列表， 传参数时：
    # 1.1 subprocess.run([script_path, "argument"], shell=True, check=True)
    # 2.2 subprocess.run(["your_script.sh", "arg1", "arg2"], check=True)
# subprocess.run(['bash', script_path], check=True)
# 2. 直接
subprocess.run(script_path, shell=True, check=True)#这种需要import os，用abspath，不然找不到。。

deltaT=[0.001, 0.002, 0.003, 0.007]
# time = np.loadtxt("./damBreak_0.001/time_0.001.x")
# 注意Courant Number mean在时间循环之前多一步，跳过
# max_co = np.loadtxt("./damBreak_0.001/max_co_0.001.txt",skiprows=1)

# # 选择 deltaT 列表中的第一个值，作为文件路径的一部分
# time_file_path = f"./damBreak_{deltaT[0]}/time_{deltaT[0]}.x"
# max_co_file_path = f"./damBreak_{deltaT[0]}/max_co_{deltaT[0]}.txt"
# time = np.loadtxt(time_file_path)
# max_co = np.loadtxt(max_co_file_path,skiprows=1)

# # plt.plot(time,max_co,label="max_courant")
# plt.plot(time, max_co, label="max_courant_{:.3f}".format(deltaT[0]))

# NOTE: style 1
# for dt in deltaT:
#     # 构建文件路径
#     time_file_path = f"./damBreak_{dt}/time_{dt}.x"
#     max_co_file_path = f"./damBreak_{dt}/max_co_{dt}.txt"

#     # 读取数据
#     time = np.loadtxt(time_file_path)
#     max_co = np.loadtxt(max_co_file_path, skiprows=1)

#     # 绘制图形
#     plt.plot(time, max_co, label=f"max_courant_{dt:.3f}")
# TODO: matplotlib双Y轴绘图
# plt.legend()
# plt.set_xlabel(direction="in")
# plt.ylim(0.4, 1.5)
# plt.show()


# NOTE: style 2
# 创建图形和子图
# fig, ax = plt.subplots()

# 创建图形和两个子图，共享 X 轴
# NOTE: 这样会绘制在两张子图中
# fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)

# for dt in deltaT:
#     # 构建文件路径
#     time_file_path = f"./damBreak_{dt}/time_{dt}.x"
#     max_co_file_path = f"./damBreak_{dt}/max_co_{dt}.txt"
#     pressure_file_path = f"./damBreak_{dt}/postProcessing/probes/0/p"

#     # 读取数据
#     time = np.loadtxt(time_file_path)
#     max_co = np.loadtxt(max_co_file_path, skiprows=1)
#     data_pressure = np.loadtxt(pressure_file_path, skiprows=3)
#     pressure = data_pressure[:, 1]

#     # 绘制图形
#     ax1.plot(time, max_co, label=f"max_courant_{dt:.3f}")
#     ax2.plot(time, pressure, label=f"pressure_{dt:.3f}")

# # 设置轴标签
# ax2.set_xlabel('Time')

# # 设置子图标题
# ax1.set_title('Max Courant Number')
# ax2.set_title('Pressure')

# # 显示图例
# ax1.legend()
# ax2.legend()

# # 调整布局
# plt.tight_layout()
# plt.show()

# NOTE: 同一张图中
# 创建图形和第一个 Y 轴
fig, ax1 = plt.subplots()
# 创建并绘制第二个 Y 轴的图形
ax2 = ax1.twinx()
# 用于存储所有的 ax2 和对应的标签
handles_ax2 = []
# 颜色循环，确保每个 dt 对应的颜色一致
colors = plt.cm.viridis(np.linspace(0, 1, len(deltaT)))

# 标记循环
markers = ['o', 's', '^','*']

for i, dt in enumerate(deltaT):
    # 构建文件路径
    time_file_path = f"./damBreak_{dt}/time_{dt}.x"
    max_co_file_path = f"./damBreak_{dt}/max_co_{dt}.txt"
    pressure_file_path = f"./damBreak_{dt}/postProcessing/probes/0/p"

    # 读取数据
    time = np.loadtxt(time_file_path)
    max_co = np.loadtxt(max_co_file_path, skiprows=1)
    data_pressure = np.loadtxt(pressure_file_path, skiprows=3)
    pressure = data_pressure[:, 1]

    # 绘制第一个 Y 轴的图形
    ax1.plot(time, max_co, label=f"max_courant_{dt:.3f}", color=colors[i])

    # 绘制第二个 Y 轴的图形
    ax2.plot(time, pressure, label=f"pressure_{dt:.3f}", linestyle='dashed', marker=markers[i],markevery=20, color=colors[i])

    # 将当前标签添加到 handles_ax2 中
    handles_ax2.append(f"pressure_{dt:.3f}")

# 设置轴标签
ax1.set_xlabel('Time')

# 设置第一个 Y 轴标签
ax1.set_ylabel('Max Courant Number', color='black')
ax1.tick_params('y', colors='black', direction="in")

# 设置第二个 Y 轴标签
ax2.set_ylabel('Pressure', color='black')
ax2.tick_params('y', colors='black', direction="in")

# 添加图例
handles_ax1, labels_ax1 = ax1.get_legend_handles_labels()
handles_ax2, labels_ax2 = ax2.get_legend_handles_labels()

# 合并图例
handles = handles_ax1 + handles_ax2
labels = labels_ax1 + labels_ax2

# 创建图例
ax1.legend(handles, labels, loc='upper right')

plt.title("Courant Number max vs Pressure")
# 调整布局，（解决title显示不）
fig.tight_layout()
# plt.show()
plt.savefig("CFL_Pressure.png",dpi=600)